<?php
namespace Common\Model;
use Think\Model;
class EntModel extends Model {
	protected $connection = 'DB_BASE_DSN';
	protected $tableName = 'qyx_ent'; 
	
	public function getAllEnt(){
		$result = $this->field('entid,entname,custnum,custid,mcustid,status,createtime,updatetime')->select();
		return $result;
	}
	
	public function getEntByCust($custid){
		$custid = (int)$custid;
		$sql = "SELECT qyx_ent.entid,qyx_ent.entname,qyx_ent.custnum,qyx_ent.custid,qyx_ent.mcustid,qyx_ent.status,qyx_ent.createtime,qyx_ent.updatetime
				FROM qyx_ent LEFT JOIN qyx_ent_cust ON qyx_ent_cust.entid=qyx_ent.entid
				WHERE qyx_ent_cust.custid={$custid}";
		$result = $this->query($sql);
		return $result;
	}
	
	public function getAllEntByCust($custid){
		$custid = (int)$custid;
		$sql = "SELECT entid,entname,custnum,custid,mcustid,status,createtime,updatetime
				FROM qyx_ent
				WHERE custid={$custid}
				UNION
				SELECT qyx_ent.entid,qyx_ent.entname,qyx_ent.custnum,qyx_ent.custid,qyx_ent.mcustid,qyx_ent.status,qyx_ent.createtime,qyx_ent.updatetime
				FROM qyx_ent LEFT JOIN qyx_ent_cust ON qyx_ent_cust.entid=qyx_ent.entid
				WHERE qyx_ent_cust.custid={$custid}";
		$result = $this->query($sql);
		return $result;
	}
	
	public function getNonExistEnt($custid){
		$custid = (int)$custid;
		$sql = "SELECT qyx_ent.entid,qyx_ent.entname,qyx_ent.custnum,qyx_ent.custid,qyx_ent.status,qyx_ent.createtime,qyx_ent.updatetime
				FROM qyx_ent LEFT JOIN qyx_ent_cust ON qyx_ent_cust.entid=qyx_ent.entid and qyx_ent_cust.custid={$custid}  
				where qyx_ent_cust.entid is null and qyx_ent.entid in(select entid from qyx_ent_department)
				";
		$result = $this->query($sql);
		return $result;
	}
	
	public function getEntById($entid){
		$map['entid'] = $entid;
		$result = $this->field('entid,entname,custnum,custid,mcustid,status,chatid,createtime,updatetime')->where($map)->find();
		return $result;
	}
	
	public function addEnt($data){
		$result = $this->add($data);
		return $result;
	}
	
	
	public function updateEnt($data){
		$map['entid'] = $data['entid'];
		$data['updatetime'] = date("Y-m-d H:i:s");
		$result = $this->where($map)->save($data);
		return $result;
	}
	
	public function deleteEnt($data){
		$map['entid'] = $data['entid'];
		$result = $this->where($map)->delete();
		return $result;
	}
	
	
	public function custNumInr($entid , $num){
		$sql = "update qyx_ent set custnum=custnum+{$num} where entid = {$entid}";
		$this->execute($sql);
	}
	
	public function custNumDecr($entid , $num){
		$sql = "update qyx_ent set custnum=custnum-{$num} where entid = {$entid}";
		$this->execute($sql);
	}
	
	

}


